package com.appcheck.recording.listener.impl;

import java.util.List;

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

import com.appcheck.recording.ListenerManager;
import com.appcheck.recording.PreViewManager;
import com.appcheck.recording.WidgetHelper;
import com.appcheck.recording.action.impl.TouchAction;
import com.appcheck.recording.listener.AbstractListener;
import com.appcheck.recording.model.IdNamePair;
import com.appcheck.recording.utils.DisplaySizeManager;
import com.appcheck.recording.utils.Logger;

public final class TouchListener extends AbstractListener implements
		OnTouchListener {
	
	private int b;
	
	public TouchListener(View paramView){
	  super(paramView, View.class, View.OnTouchListener.class);
  	}
	
	public TouchListener(View paramView, PreViewManager preViewManager) {
		super(paramView, View.class, View.OnTouchListener.class);
		super.setPreViewManager(preViewManager);
		if(preViewManager != null){
			//Logger.INFO(preViewManager.toString());
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (this.b++ > 1) {
			Logger.INFO("b++ > 1;b++ = " + b);
			return false;
		}
	    TouchAction touchAction = new TouchAction();
	    touchAction.setCatchTime(System.currentTimeMillis());
	    touchAction.setActionCode(event.getAction());
	    touchAction.setView(v);
	    touchAction.setResourceId(WidgetHelper.getResourceId(v));
	    float f1 = v.getContext().getResources().getConfiguration().orientation ==  
	    		android.content.res.Configuration.ORIENTATION_LANDSCAPE? 
	    		DisplaySizeManager.getWidth() - event.getRawY() : event.getRawX();
	    

	    float f2 = v.getContext().getResources().getConfiguration().orientation == 
	    		android.content.res.Configuration.ORIENTATION_LANDSCAPE ? 
	    		event.getRawX() : event.getRawY();
	    
	    touchAction.setX(f1);
	    touchAction.setY(f2);
	    if(this.getPreViewManager() != null){
	    	touchAction.setPreViewArray(this.getPreViewManager().getIdNameList().toArray(new IdNamePair[this.getPreViewManager().getIdNameList().size()]));
	    	touchAction.setIndex(this.getPreViewManager().getIndexInAdapterView());
	    }

	    ListenerManager.getListenerManager().handleAction(touchAction);
	    
	    if (this.listener != null){
	    	boolean hasConsumed = ((View.OnTouchListener)this.listener).onTouch(v, event);
	    	//Logger.INFO(v.toString() + " return " + String.valueOf(hasConsumed));
	    	this.b = 0;
	    	return hasConsumed;
	    }
	    this.b = 0;
	    //Logger.INFO(v.toString() + " return " + String.valueOf(false));
	    return false;
	}

}
